<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta name="baidu-site-verification" content="bk1wz1wzS4">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">



<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css">


  <meta name="keywords" content="学习,">








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0">






<meta name="description" content="从数组到对象&amp;gt;&amp;gt;&amp;gt; var myarr = [‘red’,’blue’,’yellow’,’purple’];&amp;gt;&amp;gt;&amp;gt; myarr;[“red”,”blue”,”yellow”,”purple”]&amp;gt;&amp;gt;&amp;gt; myarr[0]“red”&amp;gt;&amp;gt;&amp;gt; myarr[3]“purple”对象的情况跟数组很类似，唯一的不同是它的键值类型是自定义的。也就是说，我们的索引方式">
<meta name="keywords" content="学习">
<meta property="og:type" content="article">
<meta property="og:title" content="对象">
<meta property="og:url" content="https://youandme66.github.io/2017/02/18/second/index.html">
<meta property="og:site_name" content="腊月的季节">
<meta property="og:description" content="从数组到对象&amp;gt;&amp;gt;&amp;gt; var myarr = [‘red’,’blue’,’yellow’,’purple’];&amp;gt;&amp;gt;&amp;gt; myarr;[“red”,”blue”,”yellow”,”purple”]&amp;gt;&amp;gt;&amp;gt; myarr[0]“red”&amp;gt;&amp;gt;&amp;gt; myarr[3]“purple”对象的情况跟数组很类似，唯一的不同是它的键值类型是自定义的。也就是说，我们的索引方式">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-02-22T04:28:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="对象">
<meta name="twitter:description" content="从数组到对象&amp;gt;&amp;gt;&amp;gt; var myarr = [‘red’,’blue’,’yellow’,’purple’];&amp;gt;&amp;gt;&amp;gt; myarr;[“red”,”blue”,”yellow”,”purple”]&amp;gt;&amp;gt;&amp;gt; myarr[0]“red”&amp;gt;&amp;gt;&amp;gt; myarr[3]“purple”对象的情况跟数组很类似，唯一的不同是它的键值类型是自定义的。也就是说，我们的索引方式">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: 'youandme'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://youandme66.github.io/2017/02/18/second/">





  <title> 对象 | 腊月的季节 </title>
  <script>
  (function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>
</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">腊月的季节</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope="" itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://youandme66.github.io/2017/02/18/second/">

  <span style="display:none" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
    <meta itemprop="name" content="腊月的季节">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="腊月的季节">
    <span style="display:none" itemprop="logo" itemscope="" itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="腊月的季节" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                对象
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-02-18T00:00:00+08:00">
                2017-02-18
              </time>
            

            

            
          </span>

          
            <span class="post-category">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
            <!--noindex-->
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                  <a href="/2017/02/18/second/#comments" itemprop="discussionUrl">
                    <span class="post-comments-count hc-comment-count" data-xid="2017/02/18/second/" itemprop="commentsCount"></span>
                  </a>
                </span>
              </span>
              <!--/noindex-->
            
          

          

          
          
             <span id="/2017/02/18/second/" class="leancloud_visitors" data-flag-title="对象">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">阅读次数 </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="从数组到对象"><a href="#从数组到对象" class="headerlink" title="从数组到对象"></a>从数组到对象</h3><p>>&gt;&gt; var myarr = [‘red’,’blue’,’yellow’,’purple’];<br>>&gt;&gt; myarr;<br>[“red”,”blue”,”yellow”,”purple”]<br>>&gt;&gt; myarr[0]<br>“red”<br>>&gt;&gt; myarr[3]<br>“purple”<br>对象的情况跟数组很类似，唯一的不同是它的键值类型是自定义的。也就是说，我们的索引方式不再局限于数字了，而可以使用一些更为人性化的键值，比如first_name,age等。<br>示例:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> hero = &#123;</span><br><span class="line">    breed : <span class="string">'Turtle'</span>,</span><br><span class="line">    occupation: <span class="string">'Ninja'</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>正如我们所见:</p>
<ul>
<li>这里有一个用于表示该对象的变量名hero。</li>
<li>与定义数组时所用的中括号[]不同，对象使用的是大括号{}。</li>
<li>括号中用逗号分割着的是组成该对象的元素(通常被称之为属性)。</li>
<li>键/值对之间用冒号分割，例如,key:value。<br>有时候，我们还可以在键值(属性名)上面加一对引号，例如，下面三行代码所定义的内容是完全相同的:<br>var o = {prop:1};<br>var o = {“prop”:1};<br>var o = {‘prop’:1};<br>如果我们所选的属性名不符合JavaScript中的变量名规则，就必须对其施加一对引号。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123;</span><br><span class="line">    something: <span class="number">1</span>,</span><br><span class="line">    <span class="string">'yes or no'</span>:<span class="string">'yes'</span>,</span><br><span class="line">    <span class="string">'!#%^^&amp;*'</span>: <span class="literal">true</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>该对象合法。</p>
<h3 id="元素，属性，方法"><a href="#元素，属性，方法" class="headerlink" title="元素，属性，方法"></a>元素，属性，方法</h3><p>对象的属性也可以是一个函数，因为函数本身也是一种数据，在这种情况下，我们会称该属性为方法，例如:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> dog = &#123;</span><br><span class="line">    name : <span class="string">'Benji'</span>,</span><br><span class="line">    talk : <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        alert(<span class="string">'woof,woof!'</span>);</span><br><span class="line">&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>当然我们也可以像下面这样，在数组中存储一些函数元素并在需要时调用它们，这在实践中并不多见。<br>>&gt;&gt; var a = [];<br>>&gt;&gt; a[0] = function(what){alert(what);};<br>>&gt;&gt; a<a href="&#39;Boo!&#39;">0</a>;</p>
<h3 id="哈希表、关联型数组"><a href="#哈希表、关联型数组" class="headerlink" title="哈希表、关联型数组"></a>哈希表、关联型数组</h3><ul>
<li>一般性数组，也叫做索引型数组或者枚举型数组(通常以数字为键值)</li>
<li>关联型数组，也叫做哈希表(通常以字符串为键值)<h3 id="访问对象属性"><a href="#访问对象属性" class="headerlink" title="访问对象属性"></a>访问对象属性</h3></li>
<li>一种是中括号表示法，例如hero[‘ocuupation’]</li>
<li>另一种则是点号表示法，例如hero.occupation<br>尽管相对而言，点号表示法更易于读写，但也不是总能适用的。其中的属性和命名原则相同，即如果我们所访问的属性没有一个合法的名字，它就不能通过点号表示访问。<br>让我们来看一个具体的对象:<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> hero = &#123;</span><br><span class="line">    breed: <span class="string">'Turtle'</span>,</span><br><span class="line">    occupation:<span class="string">'Ninja'</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>下面我们用点号表示法来访问操作:<br>>&gt;&gt; hero.breed;<br>“Turtle”<br>再用中括号表示法来访问属性:<br>>&gt;&gt; hero[‘occupation’];<br>“Ninja”<br>如果我们访问的属性不存在，代码就会返回undefined。<br>>&gt;&gt; ‘Hair color is’+hero.hair_color;<br>‘Hair color is undefined’<br>另外，由于对象中可以包含任何类型的数据，自然也包括其他对象：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> book =　&#123;</span><br><span class="line">    name: <span class="string">'Catch-22'</span>,</span><br><span class="line">    published: <span class="number">1961</span>,</span><br><span class="line">    author: &#123;</span><br><span class="line">    firstname:<span class="string">'Joseph'</span>,</span><br><span class="line">    lastname: <span class="string">'Heller'</span>    </span><br><span class="line">&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>在这里，如果我们想访问book对象的author属性对象的firstname需要这样:<br>>&gt;&gt; book.author.firstname<br>‘Joseph’<br>当然，也可以连续使用中括号表示法，例如:<br>>&gt;&gt; book[‘author’][‘lastname’]<br>‘Heller’<br>甚至可以混合使用这两种表示法，例如:<br>>&gt;&gt; book.author[‘lastname’]<br>‘Heller’<br>>&gt;&gt; book[‘author’].lastname<br>‘Heller’<br>另外还有一种情况，即如果我们要访问的属性名是不确定的，就必须使用中括号表示法了，它允许我们在运行时通过变量来实现相关属性的动态存取。<br>>&gt;&gt; var key = ‘firstname’;<br>>&gt;&gt; book.author[key];<br>“Joseph”</p>
<h3 id="调用对象方法"><a href="#调用对象方法" class="headerlink" title="调用对象方法"></a>调用对象方法</h3><p>由于对象方法实际上只是一个函数类型属性，因此它们的访问方式与属性完全相同。即用点号表示法或中括号表示法均可。而其调用方式也与其他函数相同，在指定的方法名后加一对括号即可。例如下面的say方法:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> hero = &#123;</span><br><span class="line">    breed:<span class="string">'Turtle'</span>,</span><br><span class="line">    occuptation:<span class="string">'Ninja'</span>,</span><br><span class="line">    say:<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'I am '</span> + hero.occupation;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>>&gt;&gt; hero.say();<br>‘I am Ninja’<br>如果调用方法时需要传递一些参数，做法也和一般函数一样，例如:<br>>&gt;&gt; hero.say(‘a’,’b’,’c’);<br>另外，由于我们可以像访问数组一样用中括号来访问属性，因此这意味着我们同样可以用中括号来调用方法，尽管这种做法在实践中并不常见。<br>>&gt;&gt; hero<a href="">‘say’</a>;</p>
<h3 id="修改属性与方法"><a href="#修改属性与方法" class="headerlink" title="修改属性与方法"></a>修改属性与方法</h3><p>首先创建一个空对象:<br>>&gt;&gt; var hero={};<br>这时候，如果我们访问一个不存在的属性，就会:<br>>&gt;&gt; typeof hero.breed<br>“undefined”<br>现在，我们来为该对象添加一些属性和方法:<br>>&gt;&gt; hero.breed = ‘turtle’;<br>>&gt;&gt; hero.name = ‘Leonardo’;<br>>&gt;&gt; hero.sayName = function() {return hero.name;};<br>然后调用该方法:<br>>&gt;&gt; hero.sayName();<br>‘Leonardo’<br>接下来，我们删除一个属性;<br>>&gt;&gt; delete hero.name;<br>true<br>然后再调用该方法，它就不能正常工作了;<br>>&gt;&gt; hero.sayName();<br>reference to undefined property hero.name</p>
<h3 id="使用this值"><a href="#使用this值" class="headerlink" title="使用this值"></a>使用this值</h3><p>当我们处于某个对象方法内部时，还可以用另外一种方法来访问同一对象的属性，即该对象的特殊值this。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> hero = &#123;</span><br><span class="line">    name: <span class="string">'Rafaelo'</span>,</span><br><span class="line">    sayName:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.name;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>>&gt;&gt; hero.sayName();<br>‘Rafaelo’<br>也就是说，当我们引用this值时，实际上所引用的就是“这个对象”或者“当前对象”。</p>
<h3 id="构造器函数"><a href="#构造器函数" class="headerlink" title="构造器函数"></a>构造器函数</h3><p>我们可以通过构造函数的方式来创建对象，下面来看一个例子:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Hero</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.occupation=<span class="string">'Ninja'</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>为了能使用该函数来创建对象，我们需要使用new操作符，例如:<br>>&gt;&gt; var hero =new Hero();<br>>&gt;&gt; hero.occupation;<br>‘Ninja’<br>使用构造器函数的好处在于，它可以在创建对象时接收一些参数。下面，我们就来修改一下上面的构造函数，使它可以通过接收参数的方式来设定name属性:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Hero</span> (<span class="params">name</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">    <span class="keyword">this</span>.occupation = <span class="string">'Ninja'</span>;</span><br><span class="line">    <span class="keyword">this</span>.whoAreYou=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"I'm"</span> + <span class="keyword">this</span>.name +<span class="string">"and I 'm a"</span> + <span class="keyword">this</span>.occupation;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>现在，我们就能利用同一个构造器来创建不同的对象了:<br>>&gt;&gt; var h1 = new Hero(‘Michelangelo’);<br>>&gt;&gt; var h2 = new Hero(‘Donatello’);<br>>&gt;&gt; h1.whoAreYou();<br>“I’m Michelangelo and I’m a Ninja”<br>>&gt;&gt; h2.whoAreYou();<br>“I’m Donatello and I’m a Ninja”<br>如果我们在调用一个构造器函数时忽略了new操作符，尽管不会出错，但结果可能出乎意料，例如:<br>>&gt;&gt; var h= Hero(‘Leonardo’);<br>>&gt;&gt; typeof h<br>“undefined”<br>在这种情况下，this指向的是全局 对象</p>
<h3 id="全局对象"><a href="#全局对象" class="headerlink" title="全局对象"></a>全局对象</h3><p>程序所在的宿主环境一般都会为其提供一个全局对象，而所谓的全局变量其实都只不过是该对象的属性罢了。<br>例如当程序的宿主环境是web浏览器时，它所提供的全局对象就是windows。我们来看一个实例，首先，我们在所有函数之外声明一个全局变量。<br>>&gt;&gt; var a = 1;<br>然后，我们就可以通过各种不同的方式来访问该全局变量了:</p>
<ul>
<li>可以当做一个变量a来访问。</li>
<li>也可以当做全局对象的一个属性来访问，例如window[‘a’]或window.a;<br>现在，让我们回过头去分析一下刚才那个不使用new操作符调用构造器函数的情况，那时候，this值指向的是全局对象，并且所有的属性设置都是针对this所代表window对象的。<br>也就是说，当我们声明了一个构造函数，但又不通过new调用它时，代码就会返回’undefined’<br>>&gt;&gt; function Hero(name){this.naem=name;}<br>>&gt;&gt; var h = Hero(‘Leonardo’);<br>>&gt;&gt; typeof h<br>“undefined”<br>>&gt;&gt; typeof h.name<br>h has no properties<br>由于我们在Hero中使用了this，所以这里就会创建一个全局变量(同时也是全局对象的一个属性)。<br>>&gt;&gt; name<br>“Leonardo”<br>>&gt;&gt; window.name<br>“Leonardo”<br>而如果我们使用new来调用相同的构造函数，我们就会创建一个新对象，并且this也会自动指向该对象。<br>>&gt;&gt; var h2 = new Hero(‘Michelangelo’);<br>>&gt;&gt; typeof h2<br>“object”<br>>&gt;&gt; h2.name<br>“Michelangelo”<h3 id="构造器属性"><a href="#构造器属性" class="headerlink" title="构造器属性"></a>构造器属性</h3>当我们创建对象时，实际上同时也赋予了该对象一种特殊的属性=即构造器属性，该属性实际上是一个指向用于创建该对象的构造器函数的引用。<br>>&gt;&gt; h2.constructor<br>Hero(name)<br>当然，由于构造器属性所引用的是一个函数，因此我们也可以利用它来创建一个其他新对象。例如像下面这样，大意就是:”无论对象H2<br>有没有被创建，我们都可以用它来创建另一个对象”.<br>>&gt;&gt; var h3 = new h2.constructor(‘Rafaello’);<br>>&gt;&gt; h3.name;<br>“Rafaello”<br>另外，如果对象是通过对象文本标识符创建的，那么实际上它就是由內建构造函数Object()函数所创建的。<br>>&gt;&gt; var o = {};<br>>&gt;&gt; o.constructor;<br>Object()<br>>&gt;&gt; typeof o.constructor;<br>“function”</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/学习/" rel="tag"># 学习</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/02/17/sixth/" rel="next" title="函数类型回顾">
                <i class="fa fa-chevron-left"></i> 函数类型回顾
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/02/18/first/" rel="prev" title="闭包的应用">
                闭包的应用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="hypercomments_widget"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="腊月的季节">
          <p class="site-author-name" itemprop="name">腊月的季节</p>
          <p class="site-description motion-element" itemprop="description">腊月的季节的个人博客</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">160</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">72</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              我的其他足迹
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.csdn.net/qq_33433029" title="CSDN博客" target="_blank">CSDN博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://github.com/youandme66" title="GitHub" target="_blank">GitHub</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.jianshu.com/users/767025e0c4df/timeline" title="我的简书" target="_blank">我的简书</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities" title="我的知乎" target="_blank">我的知乎</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#从数组到对象"><span class="nav-number">1.</span> <span class="nav-text">从数组到对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#元素，属性，方法"><span class="nav-number">2.</span> <span class="nav-text">元素，属性，方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#哈希表、关联型数组"><span class="nav-number">3.</span> <span class="nav-text">哈希表、关联型数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#访问对象属性"><span class="nav-number">4.</span> <span class="nav-text">访问对象属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#调用对象方法"><span class="nav-number">5.</span> <span class="nav-text">调用对象方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#修改属性与方法"><span class="nav-number">6.</span> <span class="nav-text">修改属性与方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用this值"><span class="nav-number">7.</span> <span class="nav-text">使用this值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#构造器函数"><span class="nav-number">8.</span> <span class="nav-text">构造器函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#全局对象"><span class="nav-number">9.</span> <span class="nav-text">全局对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#构造器属性"><span class="nav-number">10.</span> <span class="nav-text">构造器属性</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">腊月的季节</span>
</div>


<div class="powered-by">
   <a class="theme-link" href="http://www.jianshu.com/users/767025e0c4df/timeline">我的简书</a> 
</div>

<div class="theme-info">
  链接 -
  <a class="theme-link" href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities">
    我的知乎
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>


  



  




	

		<script type="text/javascript">
		_hcwp = window._hcwp || [];

		_hcwp.push({widget:"Bloggerstream", widget_id: 93245, selector:".hc-comment-count", label: "{\%COUNT%\}" });

		
		_hcwp.push({widget:"Stream", widget_id: 93245, xid: "2017/02/18/second/"});
		

		(function() {
		if("HC_LOAD_INIT" in window)return;
		HC_LOAD_INIT = true;
		var lang = (navigator.language || navigator.systemLanguage || navigator.userLanguage || "en").substr(0, 2).toLowerCase();
		var hcc = document.createElement("script"); hcc.type = "text/javascript"; hcc.async = true;
		hcc.src = ("https:" == document.location.protocol ? "https" : "http")+"://w.hypercomments.com/widget/hc/93245/"+lang+"/widget.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hcc, s.nextSibling);
		})();
		</script>

	





  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("EAvSG3QtXW1dqzq5WQ5CjH7S-gzGzoHsz", "2aiWv7vIfVY4CjKc49aPBHFX");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

</body>
</html>
